package com.gitee.webdav.xml;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.net.URLEncodeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.text.StrPool;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.gitee.webdav.HomeStarter;
import com.gitee.webdav.kernel.Remark;
import lombok.Data;
import lombok.experimental.Accessors;
import org.smartboot.http.common.enums.HttpStatus;

import java.io.File;
import java.util.Collections;
import java.util.List;

/**
 * @author hongda.li@hand-china.com
 */
@SuppressWarnings("SpellCheckingInspection")
@Data
@Accessors(chain = true)
@Remark("响应")
public class Response {

    @Remark("资源链接")
    @JacksonXmlProperty(localName = "href", namespace = "DAV:")
    private String href;

    @Remark("属性状态列表")
    @JacksonXmlProperty(localName = "propstat", namespace = "DAV:")
    @JacksonXmlElementWrapper(useWrapping = false)
    private List<PropertiesStatus> propertiesStatusList;

    public static Response of(File file, Properties properties) {
        return new Response()
                .relatedFile(file)
                .setPropertiesStatusList(Collections.singletonList(new PropertiesStatus()
                        .buildStatus(HttpStatus.OK)
                        .setProperties(properties)));
    }

    public Response relatedFile(@Remark("指定资源") File file) {
        // 绝对路径
        String absolutePath = file.getAbsolutePath();
        // 相对路径
        String path = CharSequenceUtil.addPrefixIfNot(FileUtil.normalize(CharSequenceUtil.removePrefix(absolutePath, HomeStarter.getRootPath())), StrPool.SLASH);
        // 引用路径
        this.href = URLEncodeUtil.encode(file.isFile()
                ? path
                : CharSequenceUtil.addSuffixIfNot(path, StrPool.SLASH));
        return this;
    }
}
